//
//  MyWalletViewController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 16/4/1.
//  Copyright © 2016年 河南大实惠电子商务有限公司. All rights reserved.
//
//controller
#import "MyWalletViewController.h"
#import "MyShiHuiBiController.h"
#import "MyRecommendFriendController.h"
#import "WhatIsShiHuiBiController.h"
//untils
#import "MTA.h"
#import "AppDelegate.h"
#import "RDVTabBarController.h"
#import "Global.h"
#import "UIColor+Hex.h"
#import "ManagerHttpBase.h"
#import "ManagerGlobeUntil.h"
#import "NSString+Conversion.h"
#import "MenuScrollView.h"
#import "MJRefresh.h"
//view
#import "MyWalletHeadView.h"
#import "MyWalletCell.h"
#import "EmptyPageView.h"
//ViewMOdel
#import "MyWalletViewModel.h"
@interface MyWalletViewController ()<UITableViewDataSource,UITableViewDelegate,MyWalletHeadViewDelegate>
{
    MenuScrollView *menu;
}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)MyWalletHeadView *headView;
@property (nonatomic, strong)MyWalletViewModel *viewModel;
@property (nonatomic) NSInteger currentPage;//分页
@property (nonatomic, strong)NSString *searchType;//请求数据类型
@property (nonatomic, strong)NSMutableArray *dataSource;//数据源
@property (nonatomic, assign)NSInteger selectedIndex;//收益按钮选中下标
@property (nonatomic)NSInteger totalCount;//总条数
@property (nonatomic,strong)EmptyPageView *emptyView;//空视图
@end

@implementation MyWalletViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title =@"我的钱包";
    [self addBackNavItem];
    [self setSubView];
    [self addRightNavItemWith:[UIImage imageNamed:@"nav_mywallet_btn"]];
    self.dataSource =[[NSMutableArray alloc]init];
    self.currentPage = 1;
    self.searchType =@"1";
    self.selectedIndex =0;
    self.totalCount = 0;
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        //请求商品详情数据
        [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                                  inView:self.view];
        //第一次进请求数据
    [self.viewModel requestMyWalletDetailDatasuccess:^(NSString *responseObjects){
        [_headView setSubViewDataWithMoneyMun:[NSString marketLastTwoByteOfStringIsZero:self.viewModel.shiHuiBiMoney] FriendNum:[NSString marketLastTwoByteOfStringIsZero:self.viewModel.recommendFriend] ];
        [self loadProfitDataWithPageNum:self.currentPage PageSize:kRequestLimit SearchType:self.searchType];
    } failure:^(NSString *failureMessage) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:failureMessage inView:self.view];
    }];
    }else{
        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:@"网络连接中断~" inView:self.view];

    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
   
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:YES];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"我的钱包"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"我的钱包"];
}
#pragma mark -- lodaData
-(void)loadProfitDataWithPageNum:(NSInteger )PageNum PageSize:(NSInteger )PageSize SearchType:(NSString *)SearchType
{

    [self.viewModel requestProfitWithPageNum:PageNum PageSize:PageSize SearchType:SearchType success:^(NSArray *successMsg) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
        [self.dataSource removeAllObjects];
        [self.dataSource addObjectsFromArray:successMsg];
        _totalCount =self.viewModel.totalCount;
        if (self.dataSource.count ==0) {
            _tableView.tableFooterView = _emptyView;
        }else{
            UIView *footView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 0.1)];
            _tableView.tableFooterView =footView;
        }
        [_tableView reloadData];
        [self endRefresh];
    } failure:^(NSString *failureMessage) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:failureMessage inView:self.view];
        [self endRefresh];
    }];
    
}

#pragma mark -- MyWalletHeadViewDelegate
-(void)shiHuiBiBackGroundBtnJump
{
    MyShiHuiBiController *ShiHuiBiVc =[[MyShiHuiBiController alloc]init];
    ShiHuiBiVc.shiHuiBiNum =self.viewModel.shiHuiBiMoney;
    [self.navigationController pushViewController:ShiHuiBiVc animated:YES];
}
-(void)firendBackGroundbtnJump
{
    MyRecommendFriendController *MyRecommendFriendVc =[[MyRecommendFriendController alloc]init];
    MyRecommendFriendVc.recommendFriendNum =self.viewModel.recommendFriend;
    MyRecommendFriendVc.userLevel =self.userLevel;
    [self.navigationController pushViewController:MyRecommendFriendVc animated:YES];
}
#pragma mark -- UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"MyWalletCell";
    NSDictionary *dataDic =[self.dataSource objectAtIndex:indexPath.row];
    MyWalletCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
       cell = [[MyWalletCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        cell.backgroundColor =[UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [cell setSubViewWithTitleText:[dataDic objectForKey:@"titleText"] BadyText:[dataDic objectForKey:@"badyText"] ShiHuiBiText:[dataDic objectForKey:@"moneyText"]];
    return cell;
}
//切换收益类型
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
        return HightScalar(50);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *views = [[UIView alloc]init];
    views.backgroundColor = [UIColor whiteColor];
    NSArray *titles = @[@"我的购物收益",@"好友购物收益"];
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    //初始化menuScrollView
    CGRect menuScrollViewFrame = CGRectMake(0, 0, self.view.bounds.size.width, HightScalar(50));
    menu = [[MenuScrollView alloc]initWithFrame:menuScrollViewFrame titles:titles dataScrollView:scrollView];
    menu.backgroundColor = [UIColor whiteColor];
    menu.selectIndex = self.selectedIndex;
    menu.showBottomLine = YES;
    menu.showVerticalLine = NO;
    menu.menuScrollDelegate = (id<MenuScrollViewDelegate>)self;
    menu.bottomLineColor =[UIColor colorWithHexString:@"#db3b34"];
    menu.tabBackgroundColor = [UIColor colorWithHexString:@"#ffffff"];
    menu.tabSelectedBackgroundColor = [UIColor colorWithHexString:@"#fffff"];
    menu.tabSelectedTitleColor  = [UIColor colorWithHexString:@"#db3b34"];
    menu.tabTitleColor = [UIColor colorWithHexString:@"#555555"];
    [views addSubview:menu];
    return views;
}
- (void)selectedMenuItemAtIndex:(NSInteger)index
{
    self.selectedIndex = index;
    if (index ==0) {
        self.searchType =@"1";
    }else{
        self.searchType =@"2";
    }
    //请求数据
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                              inView:self.view];
    [self.viewModel requestProfitWithPageNum:self.currentPage PageSize:kRequestLimit SearchType:self.searchType success:^(NSArray *successMsg) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
        [self.dataSource removeAllObjects];
        [self.dataSource addObjectsFromArray:successMsg];
        if (self.dataSource.count ==0) {
            _tableView.tableFooterView= _emptyView;
        }else{
            UIView *footView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, 0.1)];
            _tableView.tableFooterView =footView;
        }
        [self performSelector:@selector(delayMethod) withObject:nil afterDelay:0.2f];
       
    } failure:^(NSString *failureMessage) {
        [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:failureMessage inView:self.view];
        
    }];
   
}
-(void)delayMethod{
     [_tableView reloadData];
}
#pragma mark - 上拉/下拉  更新数据
-(void)headerRereshing {
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        self.currentPage = 1;
        [self loadProfitDataWithPageNum:self.currentPage PageSize:kRequestLimit SearchType:self.searchType];
    }else{
        [self endRefresh];
    }
    
}

-(void)footerRereshing
{
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        if (self.currentPage*kRequestLimit < self.totalCount) {
            self.currentPage++;
      [self loadProfitDataWithPageNum:self.currentPage PageSize:kRequestLimit SearchType:self.searchType];
        } else {
        [_tableView setFooterRefreshingText:@"已加载完全部数据~"];
            [self endRefresh];
        }
    }else{
        [self endRefresh];
    }
}
- (void)endRefresh
{
    [_tableView headerEndRefreshing];
    [_tableView footerEndRefreshing];
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return HightScalar(67);
}
-(void)setSubView
{
    _tableView =[[UITableView  alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT -64) style:UITableViewStyleGrouped];
    _tableView.backgroundColor =[UIColor colorWithHexString:@"#efefef"];
    _tableView.delegate =self;
    _tableView.dataSource =self;
    _headView =[[MyWalletHeadView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, HightScalar(125))];
    _headView.delegate = self;
    _tableView.tableHeaderView =_headView;
    //添加下拉刷新
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //添加上拉加载更多
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    _emptyView =[[EmptyPageView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT-HightScalar(175)-64) EmptyPageViewType:kMyWalletNoDataView];
    _emptyView.backgroundColor=[UIColor colorWithHexString:@"#efefef"];
    _tableView.tableFooterView = _emptyView;
    [self.view addSubview:_tableView];

    
}
- (MyWalletViewModel*)viewModel {
    if (!_viewModel) {
        _viewModel = [[MyWalletViewModel alloc]init];
    }
    return _viewModel;
}
-(void)backBtnAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)rigthBtnAction:(id)sender
{
    WhatIsShiHuiBiController *Vc = [[WhatIsShiHuiBiController alloc]init];
    Vc.userLevel = self.userLevel;
    [self.navigationController pushViewController:Vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
